import {onMessage, sendMessage} from 'webext-bridge/background'
import type {Tabs} from 'webextension-polyfill'
import {webRequest} from 'webextension-polyfill'

// only on dev mode
if (import.meta.hot) {
    // @ts-expect-error for background HMR
    import('/@vite/client')
    // load latest content script
    import('./contentScriptHMR')
}
// browser.runtime.onInstalled.addListener((): void => {
//   tabs.getCurrent().then((tab) => {
//     browser.scripting.executeScript({
//       target: { tabId: tab.id },
//       func(...args): any {
//         alert('???')
//       },
//     })
//   })
//   console.log('Extension installed')
// })

let previousTabId = 0
// 修改 User-Agent
webRequest.onBeforeSendHeaders.addListener((details) => {
    // console.log(details)
    for (let i = 0; i < details.requestHeaders.length; ++i) {
        if (details.requestHeaders[i].name === 'User-Agent') {
            // 修改 User-Agent
            details.requestHeaders[i].value = 'Mozilla/5.0 (Linux; Android 10; Redmi K30 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.210 Mobile Safari/537.36'
            break
        }
    }
    return {requestHeaders: details.requestHeaders}
}, {urls: ['https://pages.tmall.com/wow/tessera/trending-center-page']}, ['blocking', 'requestHeaders'])
// webRequest.onBeforeSendHeaders.addListener(
//     function(details) {
//       for (let i = 0; i < details.requestHeaders.length; ++i) {
//         if (details.requestHeaders[i].name === 'User-Agent') {
//           details.requestHeaders[i].value = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Qianniu/9.29.02QNM Safari/537.36';
//           break;
//         }
//       }
//       return { requestHeaders: details.requestHeaders };
//     },
//     { urls: ['<all_urls>'] },
//     ['blocking', 'requestHeaders']
// );
// communication example: send previous tab title from background page
// see shim.d.ts for type declaration

browser.tabs.onActivated.addListener(async ({tabId}) => {
    if (!previousTabId) {
        previousTabId = tabId
        return
    }

    let tab: Tabs.Tab

    try {
        tab = await browser.tabs.get(previousTabId)
        previousTabId = tabId
    } catch {
        return
    }

    sendMessage('tab-prev', {title: tab.title}, {
        context: 'content-script',
        tabId,
    })
})
onMessage('get-cookie', async (message: any) => {
    // console.log(message)
    // return message
    const cookie = await browser.cookies.get({
        url: message.data.url,
        name: message.data.name,
    })
    return cookie?.value
})
onMessage('fetch', async (message: any): Promise<any> => {
    return new Promise((resolve, reject) => {
        fetch(message.data.url, {
            method: message.data.method,
            headers: message.data.headers,
            body: message.data.body,
        }).then((response) => {
            response.text().then((text) => {
                resolve(text);
            });
        }).catch((error) => {
            reject(error);
        });
    });
});
// 获取当前标签页
onMessage('get-current-tab', async (): Promise<any> => {
    try {
        const tab = await browser.tabs.get(previousTabId)
        return {
            title: tab?.title,
            id: tab?.id,
        }
    } catch {
        return null;
    }
})
